#include "photoviewwidget.h"

PhotoViewWidget::PhotoViewWidget(QWidget *parent) : QWidget(parent)
{
    this->initUI();
    this->resize(600,900);
}

void PhotoViewWidget::initUI()
{
    this->con=MyControl::getInstance();
    this->title = new QLabel("现场照片界面", this);
    this->ret_button=new QPushButton(QIcon("../image_tool/return-button.png"),"",this);
    this->ret_button->setMaximumWidth(30);
    this->text = new QLabel("请输入日期", this);
    this->date_button = new QPushButton("", this);

    //this->calendarWidget=new QCalendarWidget(this);

    this->listWidget = new QListWidget(this); // 列表父为窗口，由布局管理
    listWidget->setResizeMode(QListView::Adjust); // 自动调整大小
    this->more_button = new QPushButton("加载更多", this);

//    this->ensure = new QPushButton("确定", this);
//    this->cancel = new QPushButton("取消", this);

    /******************** 2. 初始化控件属性 ********************/
    date_button->setMinimumSize(150, 40); // 日期按钮尺寸
    listWidget->setMinimumHeight(400);    // 列表最小高度
   // listWidget->addItem("2025-03-10 14:30 执法录像"); // 测试数据



    //字体设置
    QFont font;
    font.setPixelSize(40);
    font.setBold(true);//字体加粗
    title->setFont(font);



    /******************** 3. 创建布局（子布局无父，主布局父为窗口） ********************/
    this->layout_H1 = new QHBoxLayout();
    this->layout_H2 = new QHBoxLayout();
    this->layout_H3 = new QHBoxLayout();
    this->layout_H4 = new QHBoxLayout();
    this->layout_H5 = new QHBoxLayout();
    this->layout_V = new QVBoxLayout(this);

    /******************** 4. 填充子布局内容 ********************/
    // 标题行
    layout_H1->addWidget(title);
    layout_H1->setAlignment(Qt::AlignCenter);

    // 日期行
    layout_H2->addWidget(text);
    layout_H2->addWidget(date_button);
    layout_H2->setSpacing(20);

    // 列表行
    layout_H3->addWidget(listWidget); // 列表直接添加到水平布局

    // 分页行
    layout_H4->addWidget(more_button);
    layout_H4->setSpacing(20);

    // 按钮行
    layout_H5->addWidget(ret_button);

    layout_H5->setSpacing(20);
    this->layout_H5->addStretch();


    layout_V->addLayout(layout_H1);
    layout_V->addLayout(layout_H5);
    layout_V->addLayout(layout_H2);
    layout_V->addLayout(layout_H3);
    layout_V->addLayout(layout_H4);

    layout_V->setSpacing(25);       // 垂直间距
    layout_V->setContentsMargins(30, 30, 30, 100); // 四周边距

    calendarWidget = new QCalendarWidget(this);
    calendarWidget->setWindowFlags(Qt::Popup); // 设置为弹出窗口


//    this->listWidget=new QListWidget(this);
    this->listWidget->setViewMode(QListView::IconMode);
    this->listWidget->setFixedSize(900,400);
    listWidget->setMinimumWidth(150);
    listWidget->setFont(QFont("宋体",12));

    listWidget->setIconSize(QSize(200,250));
    QPalette pal=listWidget->palette();
    pal.setColor(QPalette::Base,Qt::transparent);//底色透明
    listWidget->setPalette(pal);
    listWidget->setAutoFillBackground(false);
    listWidget->setStyleSheet("QListWidget{border:none;}");
    listWidget->setDragEnabled(false);//禁止拖拽



    this->SelectDataBase();
    this->setLayout(layout_V);


    connect(this->date_button,&QPushButton::clicked,this,&PhotoViewWidget::showCalender);
    connect(this->calendarWidget, &QCalendarWidget::activated, this, &PhotoViewWidget::selectCalender);

    connect(this->more_button,&QPushButton::clicked,this,&PhotoViewWidget::loadMoreItems);
    connect(this->ret_button,&QPushButton::clicked,this,&PhotoViewWidget::ClickRetButton);
    connect(listWidget, &QListWidget::itemClicked, this, &PhotoViewWidget::onItemClicked);








    //*****************************美化*************************************
   // 全局样式表
        QString styleSheet = R"(
            /* 窗口背景 */
            QWidget {
                background-color: #f0f0f0;
                font-family: "Microsoft YaHei";
            }

            /* 标题样式 */
            QLabel#title {
                font-size: 40px;
                color: #333;
                padding: 10px;
                border-bottom: 2px solid #333;
            }

            /* 按钮样式 */
            QPushButton {
                background-color: #4CAF50;
                color: white;
                padding: 10px 20px;
                border-radius: 5px;
                border: none;

            }

            QPushButton:hover {
                background-color: #45a049;
            }

            QPushButton:pressed {
                background-color: #3c8d40;
            }

            /* 日期按钮样式 */
            QPushButton#date_button {
                background-color: #2196F3;
            }

            QPushButton#date_button:hover {
                background-color: #1e88e5;
            }

            /* 列表项样式 */
            QListWidget {
                border: none;
                background-color: transparent;
            }

            QListWidgetItem {
                padding: 10px;
                border-radius: 5px;
                background-color: white;
                margin: 10px;
                min-height: 260px;
            }

            QListWidgetItem:hover {
                background-color: #f0f0f0;
            }

            /* 加载更多按钮 */
            QPushButton#more_button {
                background-color: #6c757d;
            }

            QPushButton#more_button:hover {
                background-color: #5a6268;
            }
        )";
        this->setStyleSheet(styleSheet);

}

void PhotoViewWidget::SelectDataBase()
{
    this->model=this->con->getModel("Image_file");
    QString sql=QString("select *from image_files where user_id=%1 ORDER BY image_files.image_id DESC").arg(id);
    Any reslut=this->model->sqlSelect((char *)sql.toStdString().c_str());
    this->images=reslut.cast_<QList<Image*>>();

    this->listWidget->clear();
    index=0;
    curindex=0;

    QList<Image*>::iterator iter=images.begin();
    while (iter != images.end() && index < 6)
       {
           QListWidgetItem *item = new QListWidgetItem(QIcon((*iter)->getImage_path().toStdString().c_str()), (*iter)->getImage_name().toStdString().c_str(), this->listWidget);
           this->listWidget->addItem(item);
           item->setData(Qt::UserRole, (*iter)->getImage_path()); // 存储图片路径
           iter++;
           index++;
       }
       curindex = index; // 记录当前已加载的位置

       this->selectimages=images;
        more_button->setEnabled(curindex < selectimages.size()); // 更新按钮状态
}

void PhotoViewWidget::showEvent(QShowEvent *event)
{
    this->SelectDataBase();
    QWidget::showEvent(event);
}



void PhotoViewWidget::showCalender()
{
    QPoint pos=date_button->mapToGlobal(QPoint(0,date_button->height()));
    this->calendarWidget->move(pos);
    this->calendarWidget->show();
}

void PhotoViewWidget::selectCalender(const QDate &date)
{
    QString dateStr = date.toString("yyyy-MM-dd");
    date_button->setText(dateStr);
    this->calendarWidget->hide();

    //查询功能
    QList<Image*> filteredVideos;
    for (Image* image : images)
    {

           QDate imageDate = image->extractDateFromName();
           QString imageDateStr=imageDate.toString("yyyy-MM-dd");
           qDebug()<<"videoDateStr="<<imageDateStr;

           if (imageDateStr == dateStr)
           {

               filteredVideos.push_back(image);
           }
     }


    if (filteredVideos.isEmpty()) {
            QMessageBox::information(this, "提示", "按照该日期查询，未找到相关照片。");
        }
    this->selectimages=filteredVideos;
    this->listWidget->clear();
    QList<Image*>::iterator iter=filteredVideos.begin();
    this->curindex=0;
       while(iter!=filteredVideos.end()&&curindex<6)
       {
           QListWidgetItem *item=new QListWidgetItem(QIcon((*iter)->getImage_path().toStdString().c_str()),(*iter)->getImage_name().toStdString().c_str(),this->listWidget);
           item->setData(Qt::UserRole, (*iter)->getImage_path()); // 设置当前视频的索引作为用户数据
           listWidget->addItem(item);
           iter++;
           this->curindex++;
       }
       more_button->setEnabled(curindex<filteredVideos.size());


    //这里需要查询功能


}

void PhotoViewWidget::loadMoreItems()
{
    QList<Image*>::iterator iter = selectimages.begin() + curindex; // 从已加载的位置开始
       while (iter != selectimages.end()&&curindex<selectimages.size())
       {
           QListWidgetItem *item = new QListWidgetItem(QIcon((*iter)->getImage_path().toStdString().c_str()), (*iter)->getImage_name().toStdString().c_str(), this->listWidget);
           this->listWidget->addItem(item);
           iter++;
           curindex++;
       }
       if (curindex == selectimages.size()) {
           more_button->setEnabled(false); // 没有更多数据时禁用按钮
       }

         more_button->setEnabled(curindex < selectimages.size()); // 更新按钮状态
}

void PhotoViewWidget::ClickRetButton()
{
    qDebug()<<"按下";
    emit PhotoToMain();
}



void PhotoViewWidget::onItemClicked(QListWidgetItem *item)
{
    QString imagePath = item->data(Qt::UserRole).toString();
        if (imagePath.isEmpty())
            return;

        QDialog *zoomDialog = new QDialog(this);
        zoomDialog->setWindowTitle("放大图片");
        zoomDialog->resize(800, 600);       // 初始大小
        zoomDialog->setMinimumSize(400, 300); // 最小尺寸，防止过小
        zoomDialog->setWindowModality(Qt::ApplicationModal); // 保持模态

           QLabel *imageLabel = new QLabel(zoomDialog);
           imageLabel->setScaledContents(false); // 禁止自动缩放，保留原图尺寸
           imageLabel->setAlignment(Qt::AlignCenter); // 图片居中
           QPixmap pixmap(imagePath);
           if (pixmap.isNull())
           {
               imageLabel->setText("无法加载图片");
           }
           else
           {
               imageLabel->setPixmap(pixmap.scaled(zoomDialog->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
           }

           QVBoxLayout *layout = new QVBoxLayout(zoomDialog);
           layout->addWidget(imageLabel);

           zoomDialog->exec();
}

